﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;

namespace Games.WPF.UI
{
    public partial class ToolboxItem : ContentControl
    {
        #region Constructors

        static ToolboxItem()
        {
            FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(typeof(ToolboxItem),
                new FrameworkPropertyMetadata(typeof(ToolboxItem)));
        }

        public ToolboxItem()
        {
            PreviewMouseDown += new MouseButtonEventHandler(ToolboxItem_PreviewMouseDown);
            MouseMove += new MouseEventHandler(ToolboxItem_MouseMove);

            DragStartPoint = null;
        }

        #endregion

        #region Properties

        private Point? DragStartPoint { get; set; }

        #endregion

        #region Event Handlers

        private void ToolboxItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            DragStartPoint = new Point?(e.GetPosition(this));
        }

        private void ToolboxItem_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton != MouseButtonState.Pressed)
            {
                DragStartPoint = null;
            }
            if (DragStartPoint.HasValue)
            {
                Point position = e.GetPosition(this);
                if ((SystemParameters.MinimumHorizontalDragDistance <= Math.Abs((double)(position.X - this.DragStartPoint.Value.X))) ||
                     (SystemParameters.MinimumVerticalDragDistance <= Math.Abs((double)(position.Y - this.DragStartPoint.Value.Y))))
                {
                    string xamlString = XamlWriter.Save(this.Content);
                    DataObject dataObject = new DataObject("DESIGNER_ITEM", xamlString);

                    if (dataObject != null)
                    {
                        DragDrop.DoDragDrop(this, dataObject, DragDropEffects.Copy);
                    }
                }
                e.Handled = true;
            }
        }

        #endregion
    }
}
